package com.iflytek.uoamp.agent.monitor.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.log4j.Logger;
import org.hyperic.sigar.NetInterfaceConfig;
import org.hyperic.sigar.NetInterfaceStat;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;

import com.iflytek.uoamp.agent.monitor.find.obj.NetWork;

public class WinIPFinder {

	/**
	 * 获取网卡信息，并对获取的网卡信息做简单过滤
	 * @return
	 */
	public static List<NetWork> findLocalIP() {
		//获取网卡的信息
		List<NetWork> scanNetWorkList = new LinkedList<NetWork>();
		try {
			Sigar sigar = new Sigar();
			String[] netIfs = sigar.getNetInterfaceList();
			for (String netName : netIfs) {
				NetWork curNetWork = new NetWork();
				NetInterfaceConfig config = sigar.getNetInterfaceConfig(netName);
				curNetWork.setIp(config.getAddress());
				curNetWork.setName(config.getAddress());
				NetInterfaceStat statStart = sigar.getNetInterfaceStat(netName);
				curNetWork.setTransportByte(statStart.getRxBytes() + "");
				
				//如果没有 IP 则跳过;
				if(curNetWork.getIp()==null || curNetWork.getIp().equals("")){
					continue;
				}
				
				//如果没有流量 则跳过
				if(curNetWork.getTransportByte()==null || curNetWork.getTransportByte().equals("") || curNetWork.getTransportByte().equals("0")){
					continue;
				}
				
				scanNetWorkList.add(curNetWork);
			}
		} catch (SigarException e) {
			Logger.getRootLogger().error("WinIPFinder throw exception, cann't get local ip : " + ExceptionUtils.getMessage(e));
		}
		
		return scanNetWorkList;
	}
	
	public static String getMAC(){
		String osname = System.getProperty("os.name").toLowerCase();  
		if(osname.startsWith("windows")){
			try {
				return getWindowsMACAddress();
			} catch (Exception e) {
				Logger.getRootLogger().error("getMAC fail!", e);
				return null;
			} 
		}else{
			return getUnixMACAddress();
		}
		
	}
	
	
	private static String getUnixMACAddress() {  
        String mac = null;  
        BufferedReader bufferedReader = null;  
        Process process = null;  
        try {  
            // linux下的命令，一般取eth0作为本地主网卡  
            process = Runtime.getRuntime().exec("ifconfig");  
            // 显示信息中包含有mac地址信息  
            bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));  
            String line = null;  
            int index = -1;
            while ((line = bufferedReader.readLine()) != null) {  
                // 寻找标示字符串[hwaddr]  
                index = line.toLowerCase().indexOf("hwaddr");  
                if (index >= 0) {// 找到了  
                    // 取出mac地址并去除2边空格  
                    mac = line.substring(index + "hwaddr".length() + 1).trim();  
                    break;  
                }  
            }  
        } catch (IOException e) {  
            Logger.getRootLogger().error("getUnixMACAddress fail!", e); 
        } finally {  
            try {  
                if (bufferedReader != null) {  
                    bufferedReader.close();  
                }  
            } catch (IOException e1) {  
            	Logger.getRootLogger().error("close bufferedReader fail!", e1);  
            }  
            bufferedReader = null;  
            process = null;  
        }  
        return mac;  
    }  
 
  
	
	
    public static String getWindowsMACAddress()throws Exception{
    	InetAddress ia = InetAddress.getLocalHost();
        //获得网络接口对象（即网卡），并得到mac地址，mac地址存在于一个byte数组中。  
        byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();  
        //下面代码是把mac地址拼装成String  
        StringBuffer sb = new StringBuffer();  
        for(int i=0;i<mac.length;i++){  
            if(i!=0){  
                sb.append("-");  
            }  
            //mac[i] & 0xFF 是为了把byte转化为正整数  
            String s = Integer.toHexString(mac[i] & 0xFF);  
            sb.append(s.length()==1?0+s:s);  
        }  
        //把字符串所有小写字母改为大写成为正规的mac地址并返回  
        return sb.toString().toUpperCase();  
    } 
    
    public static String getWindowsHostName(){
    	 Map<String, String> map = System.getenv();
         String computerName = map.get("COMPUTERNAME");// 获取计算机名
         return computerName;
    } 
    
    public static String getHostName() throws UnknownHostException{
        String HostName = null;
		Sigar sigar = new Sigar();
        try {  
        	HostName = InetAddress.getLocalHost().getHostName();  
        } catch (Exception exc) {  
            try {  
            	HostName = sigar.getNetInfo().getHostName();  
            } catch (SigarException e) {  
            	HostName = "localhost.unknown";  
            } finally {  
                sigar.close();  
            }  
        } 
        return HostName;
   } 
}
